package com.csj.cloud.common.utils;

import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.util.EntityUtils;

import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;

/**
 * @Author:ChengshaoJie
 * @Description:
 * @Date:Created in 下午 4:11 2019/12/5 0005
 */
@Slf4j
public class HttpUtils {

    public static String getByUrl(String url) {
        String resultStr = "";
        HttpGet get = new HttpGet(url);
        try {
            get.setConfig(getConfig());
            get.addHeader("Content-Type", "text/html;charset=UTF-8");
            get.setHeader("User-Agent", "Mozilla/5.0 (Windows; U; Windows NT 5.1; zh-CN; rv:1.9.0.3) Gecko/2008092417 Firefox/3.0.3");
            HttpResponse response = null;
            if (url.startsWith("https")) {
                HttpClient httpClient = wrapClient();
                response = httpClient.execute(get);
            } else {
                response = httpClientBuilder().build().execute(get);
            }
            if (HttpStatus.SC_OK == response.getStatusLine().getStatusCode()) {
                resultStr = EntityUtils.toString(response.getEntity());
                return resultStr;
            } else {
                log.error("请求返回结果{},请求地址{},请求参数{}", response.getStatusLine().getReasonPhrase(), url);
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.error("乐高apiUrl异常{}", e);
        } finally {
            // 释放连接
            get.releaseConnection();
        }
        return null;
    }

    private static HttpClientBuilder httpClientBuilder() {
        PoolingHttpClientConnectionManager manager = new PoolingHttpClientConnectionManager();
        manager.setMaxTotal(50);
        manager.setDefaultMaxPerRoute(20);
        return HttpClientBuilder.create().setConnectionManager(manager);
    }

    /**
     * 解决HTTPS的SSL证书问题
     * */
    private static HttpClient wrapClient() {
        try {
            SSLContext ctx = SSLContext.getInstance("TLS");
            X509TrustManager tm = new X509TrustManager() {
                @Override
                public X509Certificate[] getAcceptedIssuers() {
                    return null;
                }
                @Override
                public void checkClientTrusted(X509Certificate[] arg0,
                                               String arg1) throws CertificateException {
                }
                @Override
                public void checkServerTrusted(X509Certificate[] arg0,
                                               String arg1) throws CertificateException {
                }
            };
            ctx.init(null, new TrustManager[] { tm }, null);
            SSLConnectionSocketFactory ssf = new SSLConnectionSocketFactory(
                    ctx, NoopHostnameVerifier.INSTANCE);
            CloseableHttpClient httpclient = HttpClients.custom()
                    .setDefaultRequestConfig(getConfig())
                    .setSSLSocketFactory(ssf).build();

            return httpclient;
        } catch (Exception e) {
            return HttpClients.createDefault();
        }
    }

    private static RequestConfig getConfig() {
        return RequestConfig.custom().setConnectTimeout(5000) // 设置连接超时时间
                .setConnectionRequestTimeout(5000) // 设置请求超时时间
                .setSocketTimeout(5000).setRedirectsEnabled(true)// 默认允许自动重定向
                .build();
    }
}
